import java.util.Arrays;

public class MyTestHeap {
    public int elem[];
    public int usedsize;

    public MyTestHeap() {
        this.elem = new int[10];
    }

    public void initElem(int[] array){
        if(array.length > elem.length){
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedsize++;
        }
    }
    //初始化堆
    public void  creatHeap(){
        int len = usedsize -1;
        for (int parent = (len-1)/2;  parent >= 0;  parent--) {
            shiftDown(parent,usedsize);
        }
    }
    //从父节点向下调整
    public void shiftDown(int parent,int len){
        int child = parent*2+1;
        //因为堆是完全二叉树，至少得有一个左孩子
        while ( child < len){
            //判断父节点一定有右孩子
            if(child+1 < len&& elem[child] < elem[child+1]){
                    child = child + 1;
            }
            //交换父节点和较大孩子的值
            if (elem[child] > elem[parent]){
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                parent = child;
                child = parent*2+1;
            }else{
                break;
            }
        }
    }
    //打印堆
    public void printHeap(){
        for (int i = 0; i < usedsize; i++) {
            System.out.print(elem[i]+" ");
        }
    }
    //向上调整
    private void shiftUp(int child){
        int parent = (child-1)/2;
        while (child > 0){
            if(elem[child] > elem[parent]){
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                child = parent;
                parent = (child-1)/2;
            }else {
                break;
            }
        }
    }
    //往堆里面插入元素
    public void push(int val){
        if(isfull()){
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        elem[usedsize++] = val;
        //向上调整
        shiftUp(usedsize-1);
    }
    public boolean isEmpyt(){
        return usedsize == 0;
    }
    public boolean isfull(){
        return usedsize == elem.length;
    }
    //删除堆里面的元素
    public void pop(){
        if(isEmpyt()){
            return;
        }
        swap(0,usedsize-1);
        usedsize--;
        shiftDown(0,usedsize);
    }
    private void swap(int start,int end){
        int tmp = elem[start];
        elem[start] = elem[end];
        elem[end] = tmp;
    }
    public void heapSort(){
        int end = usedsize-1;
        while (end > 0){
            swap(0,end);
            end--;
            shiftDown(0,end);
        }
    }
}
